/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Mar 12, 2012  12:24:45 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.ps.outbound
 * File Name : SyncReturndeliveryOutbService.java
 * TODO
 */
package sap.business.mm.outbound;

import java.util.ArrayList;
import java.util.List;
import jpa.entitys.synchro.staging.MmReturndeliveryOutb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.MmReturndeliveryOutbServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoStructure;
import com.sap.conn.jco.JCoTable;

/**
 * @author Chatree Siangklom of Administrator
 * Date =Nov 12, 2013 : 2:32:59 PM 
 * CreateBy=Chatree Siangklom
 * 
 * SyncReturndeliveryOutbService
 * TODO
 */
public class SyncReturndeliveryOutbService extends SynchroOutAbstract{
	
	private static final Logger log = Logger.getLogger(SyncReturndeliveryOutbService.class);
	private static MmReturndeliveryOutbServices mmReturndeliveryOutbServ = null; 
	
	/**
	 * Date =Nov 12, 2013 : 2:33:07 PM 
	 * CreateBy=Chatree Siangklom
	 * SyncReturndeliveryOutbService
	 * TODO
	 */
	public SyncReturndeliveryOutbService() {
		try {
			
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
			
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	/**
	 * (Javadoc)
	 * @see sap.business.commons.SynchroOutAbstract#SynchroToSap(com.sap.conn.jco.JCoFunction, com.sap.conn.jco.JCoTable, com.sap.conn.jco.JCoStructure, java.util.List)
	 * Date =Nov 12, 2013 : 2:33:16 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, JCoStructure jCoStructure, List<?> value_list) throws Exception {
		//Check Is not isEmpty is exit method.
		if(!jcoTable.isEmpty())
		{
			log.info("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");
			return;
		}	
		
		if(!CommonService.IsNull(value_list)){
			jCoStructure.clear();
			log.info("value_list.size : " + value_list.size());			
			log.info("table.getNumRows : " + jcoTable.getNumRows());
			log.info("table.getNumColumns : " + jcoTable.getNumColumns());
			
			MmReturndeliveryOutb model = (MmReturndeliveryOutb)value_list.get(0);
			
			jCoStructure.setValue("GRN_NUMBER", model.getPromisGrtNo());
			jCoStructure.setValue("BKTXT", model.getRemarksH());
			jCoStructure.setValue("XBLNR", model.getSupplierDoNo());
			jCoStructure.setValue("BLDAT", model.getGrtDate());
			jCoStructure.setValue("BUDAT", model.getGrtDate());
			jCoStructure.setValue("BWART", model.getSapMovType());
			
			//jCoStructure.setValue("BWART", "123");
			
			jcoTable.deleteAllRows();
			for (Object obj : value_list) 
	        {
				model = (MmReturndeliveryOutb)obj;
				log.info("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId());
				jcoTable.appendRow();
				jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
								
				jcoTable.setValue("EBELN", model.getExternalPoNo());
				jcoTable.setValue("EBELP", model.getExternalPoLineItem());
				jcoTable.setValue("MATNR", model.getItemCode());
				jcoTable.setValue("WERKS", model.getProjectPlant());				
				jcoTable.setValue("MENGE", model.getItemUmQty());				
				jcoTable.setValue("ERFME", model.getItemUm());
				jcoTable.setValue("WEMPF", model.getCheckBy());
				jcoTable.setValue("GRUND", model.getReason());
				
				if(!CommonService.IsNull(model.getRemarksD()))
					jcoTable.setValue("SGTXT", model.getRemarksD());
				else
					jcoTable.setValue("SGTXT", "-");
				
	        }
		}
				
		super.SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
	}
	
	/**
	 * (Javadoc)
	 * @see sap.business.commons.SynchroOutAbstract#CallbackMessageFromSap(com.sap.conn.jco.JCoTable)
	 * Date =Nov 12, 2013 : 2:33:20 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		List<MmReturndeliveryOutb> lst = new ArrayList<MmReturndeliveryOutb>();				
		if(jcoTable_return != null && jcoTable_return.isEmpty() == false)
		{
			log.info("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
			for(int i = 0; i < jcoTable_return.getNumRows(); i++)
			{
				jcoTable_return.setRow(i);			
				MmReturndeliveryOutb model = mmReturndeliveryOutbServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
				log.info(CommonJCOReturn.toString(jcoTable_return));
				
				if(model != null){
					model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
					model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
					model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
					model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
					model.setIsactive("Y");
					model.setIssync("Y");
					
					lst.add(model);
				}
			}
			
			mmReturndeliveryOutbServ.Updated(lst);
		}else
			log.info(CommonJCOReturn.toString(jcoTable_return));
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	/**
	 * 
	 * Date =Nov 12, 2013 : 2:33:28 PM 
	 * CreateBy=Chatree Siangklom
	 * List<MmReturndeliveryOutb>
	 * TODO
	 * @return
	 * @throws Exception
	 */
	private List<MmReturndeliveryOutb> Search() throws Exception 
	{
		try{
			
			String company = "SP";
			String project = "SPLVILLE-PRAGSA";
			String promisGrtNo = "79-1205-000001";
			String status = "A";
			String issync = "Y";
			List<MmReturndeliveryOutb> lst = mmReturndeliveryOutbServ.findByDocumentNo(company, project, promisGrtNo, status, issync);
			
			if(!CommonService.IsNull(lst))
				log.info(lst.size());
			else
				log.info(" else  ");
			
			return lst;
			
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			
			throw e;
		}
		
	}
	
	/**
	 * 
	 * Date =Nov 12, 2013 : 2:33:31 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param value_list
	 * @throws Exception
	 */
	public void SendToSAP(List<MmReturndeliveryOutb> value_list ) throws Exception
	{
		if(!CommonService.IsNull(value_list)){
			this.sap_bapi = "ZIN_MMPUR_RETURN_DL";
			
			this.sap_structure = "GI_HEAD";
			this.sap_table = "GT_ITEM";
			
			this.sap_table_return = "RETURN";
			this.jco_conn  = new Connection();
			mmReturndeliveryOutbServ = new MmReturndeliveryOutbServices(this.emSynchro);

			//Get SAP BAPI function
			JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
			
			//Get SAP Staging table or Structure
			JCoTable jcoTable = jco_conn.getTables(sap_table);
			JCoStructure jCoStructure = jco_conn.getImportStructure(sap_structure);
			
			
			//List<MmReturndeliveryOutb> value_list =  Search(); // mmReturndeliveryOutbServ.findAllIsSync("N");
			SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
			
			//Get SAP Staging table retrun message
			JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
			CallbackMessageFromSap(jcoTable_return);
		}
		
	}
	
	/**
	 * 
	 * Date =Nov 12, 2013 : 2:33:36 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @throws Exception
	 */
	private void Start() throws Exception
	{
		this.sap_bapi = "ZIN_MMPUR_RETURN_DL";
		
		this.sap_structure = "GI_HEAD";
		this.sap_table = "GT_ITEM";
		
		this.sap_table_return = "RETURN";
		this.jco_conn  = new Connection();
		mmReturndeliveryOutbServ = new MmReturndeliveryOutbServices(this.emSynchro);

		//Get SAP BAPI function
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table or Structure
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		JCoStructure jCoStructure = jco_conn.getImportStructure(sap_structure);
		
		
		List<MmReturndeliveryOutb> value_list =  Search(); // mmReturndeliveryOutbServ.findAllIsSync("N");
		SynchroToSap(jcoFunction, jcoTable, jCoStructure, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);
	}

//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub		
//		try {
//			
//			SyncReturndeliveryOutbService xx = new SyncReturndeliveryOutbService();
//			
//			xx.Start();
//			
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}		
//
//	}

}
